package com.batunite.livedatabinding

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.batunite.livedatabinding.adapter.SelectLevelAdapter
import com.batunite.livedatabinding.bean.LevelBean
import com.batunite.livedatabinding.dao.DatabaseHelper
import com.batunite.livedatabinding.databinding.ActivityMainBinding
import com.batunite.livedatabinding.model.Map90Data
import com.batunite.livedatabinding.model.TestViewModel
import com.batunite.livedatabinding.views.GridSpacingItemDecoration
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.LinkedList

/**
 *
 */
class MainActivity : AppCompatActivity() {
    private var correntLevel: Int = 0
    var mTestViewModel: TestViewModel? = null
    var alertDialog: AlertDialog? = null
    val items = arrayListOf<LevelBean>()
    val adapter = SelectLevelAdapter(items)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        mTestViewModel = ViewModelProvider(this).get(TestViewModel::class.java)
        val mNameEvent = mTestViewModel?.mNameEvent
        mNameEvent?.observe(this) {
        }
        binding.btStart.setOnClickListener {
            val intent = Intent(this@MainActivity, GameMainActivity::class.java)
            intent.putExtra("LEVEL_NUM", correntLevel)
            startActivity(intent)
        }
        binding.btSelect.setOnClickListener {
            Log.d(">>>>", "before show: ... ${System.currentTimeMillis()}")
            binding.btSelect.post {
                alertDialog?.show()
            }
            Log.d(">>>>", "after show:  ... ${System.currentTimeMillis()}")
        }
        binding.btSelect.post {
            Log.d(">>>>", "onCreate: ${Map90Data.mapDataList.size}")
            queryLevelDao(false)
            createAlertDialog()
        }
        binding.btQuit.setOnClickListener{
            startActivity(Intent(this@MainActivity, TetrisGPTActivity::class.java))
        }
    }

    /**
     * 检查数据库
     */
    private fun queryLevelDao(isNotify: Boolean = false) {
        val dbHelper = DatabaseHelper(this)
        GlobalScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                for (i in 0 until Map90Data.mapDataList.size) {
                    // 数据库id从1开始
                    val queryLevelBean = dbHelper.queryLevelBean(i + 1)
                    if (queryLevelBean == null) {
                        // 示例：插入 LevelBean 对象 默认第一关可用
                        val level = LevelBean("第${i + 1}关", i == 0)
                        val insertedId = dbHelper.insertLevel(level)
                        items.add(LevelBean(level.name, i == 0))
//                        Log.d(">>>>", "add : ${level.name}")
                    } else {
//                        Log.d(">>>>", "queryLevelBean read : ${queryLevelBean.name}")
                        if (queryLevelBean.completed) correntLevel = i
                        if (isNotify && items.isNotEmpty()) {
                            // 是更新
                            val adapterBean = items.get(i)
                            // 状态和数据库不对应
                            if (adapterBean.completed != queryLevelBean.completed) {
                                adapterBean.completed = queryLevelBean.completed
                                Log.d(">>>>", "queryLevelDao: 更新数据")
                                adapter.notifyItemChanged(i)
                            }
                        } else {
                            items.add(LevelBean(queryLevelBean.name, queryLevelBean.completed))
                        }
                    }
                }
            }
        }

        /*
        // 示例：获取所有 LevelBean 对象
        val levels = dbHelper.getAllLevels()
        for (level in levels) {
            // 处理每个 LevelBean 对象
        }
        // 示例：删除所有 LevelBean 对象
        dbHelper.deleteAllLevels()
         */

    }

    /**
     * 创建关卡选择对话框
     */
    private fun createAlertDialog() {
        // 创建对话框构建器
        val builder: AlertDialog.Builder = AlertDialog.Builder(this)
        // 加载自定义的布局文件
        val dialogView: View =
            LayoutInflater.from(this).inflate(R.layout.dialog_custom_layout, null)
        builder.setView(dialogView)
        // 初始化 RecyclerView
        val recyclerView = dialogView.findViewById<RecyclerView>(R.id.recyclerView)
        // 创建并设置 RecyclerView 的布局管理器和适配器
        val spanCount = 3
        val layoutManager = GridLayoutManager(this, spanCount)
        recyclerView.layoutManager = layoutManager
        val spacing = resources.getDimensionPixelSize(R.dimen.grid_spacing) // 获取间距大小
        Log.d(">>>>", "createAlertDialog spacing: $spacing")
        val itemDecoration = GridSpacingItemDecoration(spanCount, spacing)
        recyclerView.addItemDecoration(itemDecoration)

        recyclerView.adapter = adapter
        adapter.onItemClickListener = (object : SelectLevelAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                val get = items[position]
                if (get.completed) {
                    val intent = Intent(this@MainActivity, GameMainActivity::class.java)
                    intent.putExtra("LEVEL_NUM", position)
                    startActivity(intent)
                    alertDialog?.dismiss()
                } else {
                    Toast.makeText(this@MainActivity, "还未解锁！", Toast.LENGTH_SHORT).show()
                }
                Log.d(">>>>", "onItemClick: ${get?.name} --> ${get?.completed}")
            }
        })
        // 设置对话框其他属性和按钮等
        // 显示对话框
        alertDialog = builder.create()
    }

    override fun onResume() {
        super.onResume()
        Log.d(">>>>", "onResume: ")
        alertDialog?.let {
            // 更新一下items的数据
            Log.d(">>>>", "items 获取完毕==: ${items.size}")
            queryLevelDao(true)
        }

    }

    override fun onPause() {
        super.onPause()
        Log.d(">>>>", "onPause: ")
    }

    override fun onStop() {
        super.onStop()
        Log.d(">>>>", "onStop: ")
    }
}
